package com.societyGames.persist
{
	import com.societyGames.system.EventObject;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;

	public class SharedObjectPersist extends Persist implements IPersist
	{
		private var _path:String;
		private var _sharedObject:SharedObject;
		
		public function SharedObjectPersist(path:String)
		{
			this._path = path;
		}
		
		//IPersist-->
		public function setData(key:String, data:Object):void //Sets intermediate data.
		{
			this._sharedObject.data[key] = data;
		}
		
		public function getData(key:String):Object			//Sets intermediate data.
		{
			return this._sharedObject.data[key];
		}
		
		public function open():void							//Opens the connection to the save data.
		{
			if (this._sharedObject == null) //Not already opened.
			{
				try
				{
					this._sharedObject = SharedObject.getLocal(this._path); //"/codeHero");
					if (this._sharedObject != null)
					{	
						this._openSucceededEventObject.dispatchEvent();	
					}
					else
					{
						this._openFailedEventObject.dispatchEvent();
					}
				}
				catch (error:Error)
				{	
					this._openFailedEventObject.dispatchEvent();	
				}	
			}
			else
			{
				this._openSucceededEventObject.dispatchEvent();
			}
		}
		
		public function flush():void							//Close the save data.
		{	
			try
			{	
				var flushStatus:String = this._sharedObject.flush();
				if (flushStatus != null)
				{					
					switch(flushStatus)
					{
						case SharedObjectFlushStatus.PENDING:
							this._sharedObject.addEventListener(NetStatusEvent.NET_STATUS, sharedObjectNetStatusHandler);
							break;
						case SharedObjectFlushStatus.FLUSHED:
							this._flushSuccededEventObject.dispatchEvent();
							break;
					}
				}
			}
			catch (error:Error)
			{	
				this._flushFailedEventObject.dispatchEvent();	
			}
		}
		//<--IPersist
		
		private function sharedObjectNetStatusHandler(event:NetStatusEvent):void
		{
			this._sharedObject.removeEventListener(NetStatusEvent.NET_STATUS, sharedObjectNetStatusHandler);
			if (event.info.code == "SharedObject.Flush.Success")
			{	
				this._flushSuccededEventObject.dispatchEvent();
			}
			else if (event.info.code == "SharedObject.Flush.Failed")
			{
				this._flushFailedEventObject.dispatchEvent();
			}
		}
	}
}